<%--
  Created by IntelliJ IDEA.
  User: Administrator
  Date: 2025/5/6 0006
  Time: 11:03
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <style>
        * { margin: 0; padding: 0; box-sizing: border-box; }
        body {
            font-family: '微软雅黑';
            background: rgb(255, 255, 255);
        }
        .main-content {
            width: 100%;
            padding: 24px;
            background: #fff;
            border-radius: 8px;
            box-shadow: 0 2px 8px rgba(0,0,0,0.1);
        }
        .action-bar {
            display: flex;
            gap: 12px;
            margin-bottom: 20px;
        }
        input {
            padding: 8px 12px;
            border: 1px solid #ddd;
            border-radius: 4px;
            width: 160px;
            font-size: 13px;
        }
        button {
            padding: 8px 16px;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            font-size: 13px;
        }
        .btn-search {
            background: #1890ff;
            color: white;
        }
        .btn-new {
            background: #52c41a;
            color: white;
        }
        table {
            width: 100%;
            border-collapse: collapse;
            background: white;
            border: 1px solid #e8e8e8;
            margin-top: 12px;
        }
        th, td {
            padding: 12px 16px;
            text-align: left;
            border-bottom: 1px solid #e8e8e8;
            font-size: 13px;
        }
        th {
            background: #fafafa;
            color: rgba(0,0,0,0.85);
        }
        .action-btns button {
            padding: 4px 8px;
            margin-right: 8px;
        }
        .btn-edit {
            background: #faad14;
            color: #fff;
        }
        .btn-del {
            background: #ff4d4f;
            color: #fff;
        }
        .pagination {
            margin-top: 16px;
            color: #999;
            font-size: 13px;
        }
        .modal {
            display: none;
            position: fixed;
            z-index: 100;
            left: 0;
            top: 0;
            width: 100%;
            height: 100%;
            background-color: rgba(0,0,0,0.5);
        }
        .modal-content {
            background-color: #fff;
            margin: 10% auto;
            padding: 20px;
            border-radius: 4px;
            width: 450px;
            box-shadow: 0 2px 8px rgba(0,0,0,0.15);
        }
        .modal-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 20px;
            padding-bottom: 10px;
            border-bottom: 1px solid #e8e8e8;
        }
        .modal-title {
            font-size: 16px;
            color: rgba(0,0,0,0.85);
            font-weight: 500;
        }
        .close {
            font-size: 20px;
            color: #999;
            cursor: pointer;
        }
        .form-group {
            margin-bottom: 16px;
        }
        .form-group label {
            display: block;
            margin-bottom: 8px;
            color: rgba(0,0,0,0.85);
        }
        .form-group input, .form-group select {
            width: 100%;
            padding: 8px 12px;
            border: 1px solid #d9d9d9;
            border-radius: 4px;
            font-size: 13px;
        }
        .modal-footer {
            display: flex;
            justify-content: flex-end;
            gap: 10px;
            margin-top: 24px;
            padding-top: 16px;
            border-top: 1px solid #e8e8e8;
        }
        .btn-cancel {
            background: #fff;
            color: rgba(0,0,0,0.65);
            border: 1px solid #d9d9d9;
        }
        .btn-save {
            background: #1890ff;
            color: white;
        }
        .pagination {
            display: flex;
            align-items: center;
            gap: 16px;
            margin-top: 16px;
            color: #999;
            font-size: 13px;
        }
        .btn-prev, .btn-next {
            padding: 6px 12px;
            border: 1px solid #d9d9d9;
            border-radius: 4px;
            background: #fff;
            cursor: pointer;
            font-size: 13px;
            transition: all 0.3s;
        }
        .btn-prev:hover, .btn-next:hover {
            color: #1890ff;
            border-color: #1890ff;
        }
        .btn-prev:disabled, .btn-next:disabled {
            color: #d9d9d9;
            border-color: #d9d9d9;
            cursor: not-allowed;
        }
        #pageInfo {
            min-width: 60px;
            text-align: center;
        }
    </style>
</head>
<body>
<div class="main-content">
    <h3 style="margin-bottom:16px;color:rgba(0,0,0,0.85)">学生管理</h3>

    <div class="action-bar">
        <input placeholder="学生编号" name="xh">
        <input placeholder="姓名" name="name">
        <button class="btn-search" onclick="cx()">查询</button>
        <button class="btn-new" onclick="openAddModal()">新增</button>
        <button onclick="exportToExcel()">导出</button>
    </div>

    <table id="studentTable">
        <thead>
        <tr>
            <th>学生编号</th>
            <th>姓名</th>
            <th>性别</th>
            <th>操作</th>
        </tr>
        </thead>
        <tbody>
        <!-- 数据将通过JavaScript动态加载 -->
        </tbody>
    </table>
    <div class="pagination">
        <button class="btn-prev" onclick="page(currentPage - 1)">上一页</button>
        <span id="pageInfo">第 1 页</span>
        <button class="btn-next" onclick="page(currentPage + 1)">下一页</button>
    </div>

</div>

<!-- 修改学生信息弹窗 -->
<div id="editModal" class="modal">
    <div class="modal-content">
        <div class="modal-header">
            <h3 class="modal-title">修改学生信息</h3>
            <span class="close" onclick="closeModal('editModal')">&times;</span>
        </div>
        <div class="modal-body">
            <div class="form-group">
                <label>学生编号</label>
                <input type="text" id="editStudentNumber">
            </div>
            <div class="form-group">
                <label>姓名</label>
                <input type="text" id="editStudentName">
            </div>
            <div class="form-group">
                <label>性别</label>
                <select id="editStudentGender">
                    <option value="男">男</option>
                    <option value="女">女</option>
                </select>
            </div>
            <input type="hidden" id="editStudentId"> <!-- 隐藏的ID字段 -->
        </div>
        <!-- 添加模态框底部按钮 -->
        <div class="modal-footer">
            <button class="btn-cancel" onclick="closeModal('editModal')">取消</button>
            <button class="btn-save" onclick="saveEdit()">保存</button>
        </div>
    </div>
</div>

<!-- 新增学生信息弹窗 -->
<div id="addModal" class="modal">
    <div class="modal-content">
        <div class="modal-header">
            <h3 class="modal-title">新增学生信息</h3>
            <span class="close" onclick="closeModal('addModal')">&times;</span>
        </div>
        <div class="modal-body">
            <div class="form-group">
                <label>学生编号</label>
                <input type="text" id="addStudentId">
            </div>
            <div class="form-group">
                <label>姓名</label>
                <input type="text" id="addStudentName">
            </div>
            <div class="form-group">
                <label>性别</label>
                <select id="addStudentGender">
                    <option value="男">男</option>
                    <option value="女">女</option>
                </select>
            </div>
        </div>
        <div class="modal-footer">
            <button class="btn-cancel" onclick="closeModal('addModal')">取消</button>
            <button class="btn-save" onclick="saveAdd()">保存</button>
        </div>

    </div>
</div>

<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/xlsx@0.18.5/dist/xlsx.full.min.js"></script>
<script>

function page(pageNum) {
    // 确保页码在有效范围内
    pageNum = Math.max(0, Math.min(pageNum, window.totalPages - 1));
    var xh = $("input[name='xh']").val();
    var name = $("input[name='name']").val();
    
    $.get("<%=request.getContextPath()%>/StudentsController", {
        op: "sccx",
        xh: xh,
        name: name,
        page: pageNum
    }, function(data) {
        show(data);
    });
}

// 修改show函数，确保正确更新分页状态
function show(data) {
    var jsonData = JSON.parse(data);
    let htmls = "";
    
    // 渲染表格数据
    $.each(jsonData.list, function(index, emp) {
        htmls += '<tr data-id="' + emp.student_id + '">' +
            '<td>' + emp.student_number + '</td>' +
            '<td>' + emp.name + '</td>' +
            '<td>' + emp.gender + '</td>' +
            '<td class="action-btns">' +
            '<button class="btn-edit" onclick="openEditModal(' + emp.student_id + ', \'' + emp.student_number + '\', \'' + emp.name + '\', \'' + emp.gender + '\')">修改</button>' +
            '<button class="btn-del" onclick="deleteStudent(' + emp.student_id + ')">删除</button>' +
            '</td>' +
            '</tr>';
    });
    
    $("#studentTable tbody").html(htmls);
    
    // 更新分页信息
    $("#pageInfo").text("第 " + (jsonData.page + 1) + " 页/共 " + jsonData.totalPages + " 页");
    $(".btn-prev").prop("disabled", jsonData.page <= 0);
    $(".btn-next").prop("disabled", jsonData.page >= jsonData.totalPages - 1);
    
    // 更新全局分页变量
    window.currentPage = jsonData.page;
    window.totalPages = jsonData.totalPages;
}

    // 页面加载时查询数据
    $(document).ready(function() {
        cx();
    });

    // 搜索查询
    function cx() {
        var xh = $("input[name='xh']").val();
        var name = $("input[name='name']").val();
        $.get("<%=request.getContextPath()%>/StudentsController", {
            op: "sccx",
            xh: xh,
            name: name,
            page: 0 // 从第0页开始
        }, function(data) {
            show(data);
        });
    }


    // 打开修改弹窗
    function openEditModal(id, studentNumber, name, gender) {
        $("#editStudentId").val(id);  // 这里存储的是数据库ID
        $("#editStudentNumber").val(studentNumber);  // 需要添加这个输入框
        $("#editStudentName").val(name);
        $("#editStudentGender").val(gender);
        $("#editModal").show();
    }

    // 打开新增弹窗
    function openAddModal() {
        $("#addStudentId").val('');
        $("#addStudentName").val('');
        $("#addStudentGender").val('男');
        $("#addModal").show();
    }

    // 关闭弹窗
    function closeModal(modalId) {
        $("#" + modalId).hide();
    }

    // 修改后的保存函数
    function saveEdit() {
        const id = $("#editStudentId").val();
        const studentNumber = $("#editStudentNumber").val();
        const name = $("#editStudentName").val();
        const gender = $("#editStudentGender").val();

        if(!id) {
            alert("错误：无法获取学生ID");
            return;
        }

        $.post("<%=request.getContextPath()%>/StudentsController", {
            op: "update",
            id: id,  // 传递数字ID
            student_number: studentNumber,
            name: name,
            gender: gender
        }, function(data) {
            if(data === "success") {
                alert("修改成功");
                closeModal('editModal');
                cx(); // 刷新数据
            } else {
                alert("修改失败：" + data);
            }
        });
    }

    // 保存新增
    function saveAdd() {
        const id = $("#addStudentId").val();
        const name = $("#addStudentName").val();
        const gender = $("#addStudentGender").val();

        $.post("<%=request.getContextPath()%>/StudentsController", {
            op: "add",
            student_number: id,
            name: name,
            gender: gender
        }, function(data) {
            alert("新增成功");
            closeModal('addModal');
            cx(); // 刷新数据
        });
    }

    // 删除学生
    function deleteStudent(id) {
        if (confirm("确定要删除学号为 " + id + " 的学生吗？")) {
            $.post("<%=request.getContextPath()%>/StudentsController", {
                op: "delete",
                student_number: id
            }, function(data) {
                alert("删除成功");
                cx(); // 刷新数据
            });
        }
    }



    // 导出Excel功能
    function exportToExcel() {
        // 获取表格数据
        var table = document.getElementById("studentTable");
        var rows = table.querySelectorAll("tbody tr");

        if(rows.length === 0) {
            alert("没有数据可导出");
            return;
        }

        // 准备Excel数据
        var excelData = [
            ["学生编号", "姓名", "性别"] // 表头
        ];

        // 添加数据行
        rows.forEach(function(row) {
            var cells = row.cells;
            excelData.push([
                cells[1].innerText, // 跳过隐藏的ID列
                cells[2].innerText,
                cells[3].innerText
            ]);
        });

        // 创建工作簿
        var wb = XLSX.utils.book_new();
        var ws = XLSX.utils.aoa_to_sheet(excelData);

        // 设置列宽
        ws['!cols'] = [
            {wch: 15}, // 学生编号列宽
            {wch: 20}, // 姓名列宽
            {wch: 10}  // 性别列宽
        ];

        // 添加工作表到工作簿
        XLSX.utils.book_append_sheet(wb, ws, "学生数据");

        // 生成Excel文件并下载
        var date = new Date();
        var fileName = "学生数据_" +
            date.getFullYear() +
            (date.getMonth()+1).toString().padStart(2, '0') +
            date.getDate().toString().padStart(2, '0') +
            ".xlsx";

        XLSX.writeFile(wb, fileName);
    }

    // 点击弹窗外部关闭
    $(document).on('click', function(e) {
        if ($(e.target).hasClass('modal')) {
            $(e.target).hide();
        }
    });
</script>
</body>
</html>